﻿/*****************************************************************************
Copyright (c) 2011 SmartVault, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
******************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Google.ProtocolBuffers;
using System.Xml;
using System.Runtime.Serialization;
using Google.ProtocolBuffers.Serialization;

namespace SmartVault.Proto
{
    /// <summary>
    /// ProtoSerializer
    /// 
    /// Encapsulates the ability to serializae proto buffers in three formats:
    /// XML
    /// JSON
    /// Native
    /// </summary>
    public class ProtoSerializer
    {
        private const string XmlRootElement = "envelope";

        /// <summary>
        /// Constructor
        /// </summary>
        public ProtoSerializer()
        {
            this.UseByteOrderMark = false;
            this.Encoding = Encoding.UTF8;
            this.Format = ProtoFormats.NATIVE;
        }

        /// <summary>
        /// Should BOM be written or read. By default, this is false.
        /// </summary>
        public bool UseByteOrderMark { get; set; }

        /// <summary>
        /// Format used for serialization
        /// </summary>
        public ProtoFormats Format { get; set;}

        /// <summary>
        /// Encoding Format. Only used for JSON and XML.
        /// </summary>
        public Encoding Encoding { get; set; }

        #region Private Methods
        /// <summary>
        /// GetEncoding
        /// 
        /// Used to ensure byte order elements are not writter to the stream
        /// </summary>
        /// <param name="encoding"></param>
        /// <returns></returns>
        private Encoding GetEncoding(Encoding encoding)
        {
            if (encoding == null) return null;
            if (encoding.Equals(Encoding.UTF8))
            {
                return new UTF8Encoding(UseByteOrderMark);
            }
            else if (encoding.Equals(Encoding.UTF7))
            {
                throw new ArgumentException();  // MRW 06-04-2011 Currently Broken
                //return new UTF7Encoding(UseByteOrderMark);
            }
            else
            {
                return encoding;
            }
        }
        #endregion

        #region Public Methods
        public T Read<T>(Stream s) where T : class, IMessageLite, new()
        {
            return (T)Read(this.Format, this.Encoding, s, new T().WeakToBuilder()).WeakBuild();
        }

        public T Merge<T>(T builder, Stream s)
            where T : IBuilderLite
        {
            return Read(this.Format, this.Encoding, s, builder);
        }

        public void Write(Stream s, IMessage message)
        {
            Write(this.Format, this.Encoding, s, message);
        }

        /// <summary>
        /// Read 
        /// 
        /// Read a message
        /// </summary>
        private T Read<T>(ProtoFormats format, Encoding encoding, Stream s, T builder) where T : IBuilderLite
        {
            encoding = GetEncoding(encoding);

            if (format == ProtoFormats.XML)
            {
                XmlFormatReader reader = XmlFormatReader.CreateInstance(s); /*encoding*/
                return reader.Merge(XmlRootElement, builder, ExtensionRegistry.Empty);
            }
            else if (format == ProtoFormats.JSON)
            {
                StreamReader reader = new StreamReader(s, encoding);
                return JsonFormatReader.CreateInstance(reader).Merge(builder);
            }
            else if (format == ProtoFormats.NATIVE)
            {
                builder.WeakMergeFrom(CodedInputStream.CreateInstance(s));
                return builder;
            }
            else
            {
                throw new ArgumentException();
            }
        }

        /// <summary>
        /// Write
        /// 
        /// Write a message
        /// </summary>
        /// <param name="format"></param>
        /// <param name="encoding"></param>
        /// <param name="s"></param>
        /// <param name="message"></param>
        private void Write(ProtoFormats format, Encoding encoding, Stream s, IMessage message)
        {
            encoding = GetEncoding(encoding);

            if (format == ProtoFormats.XML)
            {
                StreamWriter text = new StreamWriter(s, encoding);
                XmlFormatWriter writer = XmlFormatWriter.CreateInstance(text);
                writer.WriteMessage(XmlRootElement, message);
                text.Flush();
            }
            else if (format == ProtoFormats.JSON)
            {
                StreamWriter writer = new StreamWriter(s, encoding);
                JsonFormatWriter.CreateInstance(writer)
                    .Formatted()
                    .WriteMessage(message);
                writer.Flush();
            }
            else if (format == ProtoFormats.NATIVE)
            {
                message.WriteTo(s);
            }
            else
            {
                throw new ArgumentException();
            }
        }
        #endregion
    }
}
